﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using JiaBao.Core.Data;
using JiaBao.Core.Domain;

namespace JiaBao.Data
{


    public class EfRepositor<T> : IRepository<T> where T : BaseEntity
    {
        #region Fields
        private readonly IDbContext _context;
        private IDbSet<T> _entities;
        #endregion

        #region 属性


        /// <summary>
        /// 获取数据集合
        /// </summary>
        public IQueryable<T> Table => Entities;

        /// <summary>
        /// 获取只读数据集合
        /// </summary>
        public IQueryable<T> TableNotracking => Entities.AsNoTracking();

        protected virtual IDbSet<T> Entities
        {
            get
            {
                if (_entities == null)
                    _entities = _context.Set<T>();
                return _entities;
            }
        }

        #endregion

        #region Ctor

        public EfRepositor(IDbContext context)
        {
            _context = context;
        }


        #endregion

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Delete(T entity)
        {
            try
            {
                if (entity == null)
                    throw new ArgumentNullException("entity");

                Entities.Remove(entity);
                return SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {

                throw new Exception(GetFullErrorText(ex), ex);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public int Delete(IEnumerable<T> entities)
        {
            try
            {
                if (entities == null)
                    throw new ArgumentNullException("entities");

                foreach (var e in entities)
                    Entities.Remove(e);

                return SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {

                throw new Exception(GetFullErrorText(ex), ex);
            }
        }

        /// <summary>
        /// 根据Id获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetById(object id)
        {
            return Entities.Find(id);
        }


        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Insert(T entity)
        {
            try
            {
                if (entity == null)
                    throw new ArgumentNullException("entity");
                Entities.Add(entity);
                return SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {

                throw new Exception(GetFullErrorText(ex), ex);
            }
        }


        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public int Insert(IEnumerable<T> entities)
        {
            try
            {
                if (entities == null)
                    throw new ArgumentNullException("entities");

                foreach (var entity in entities)
                    Entities.Add(entity);

                return SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {

                throw new Exception(GetFullErrorText(ex), ex);
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Update(T entity)
        {
            try
            {
                if (entity == null)
                    throw new ArgumentNullException("entity");

                return SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {

                throw new Exception(GetFullErrorText(ex), ex);
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public int Update(IEnumerable<T> entities)
        {
            try
            {
                if (entities == null)
                    throw new ArgumentNullException("entities");
                return SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {

                throw new Exception(GetFullErrorText(ex), ex);
            }
        }


        #region 内部方法

        /// <summary>
        /// 保存变更返回首映行行数
        /// </summary>
        /// <returns></returns>
        protected int SaveChanges()
        {
            return _context.SaveChanges();
        }

        /// <summary>
        /// 读取 DbEntityValidationException 错误
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        protected string GetFullErrorText(DbEntityValidationException ex)
        {
            var msg = string.Empty;
            foreach (var errors in ex.EntityValidationErrors)
                foreach (var error in errors.ValidationErrors)
                    msg += string.Format("属性 : {0} 错误 : {1}", error.PropertyName, error.ErrorMessage + Environment.NewLine);

            return msg;
        }

        #endregion
    }
}
